package com.lujianfei.babymilkmemory.utils

import android.content.Intent
import android.media.MediaScannerConnection
import android.net.Uri
import android.provider.MediaStore
import android.util.Log
import androidx.core.content.FileProvider
import com.lujianfei.babymilkmemory.MyApplication
import java.io.File

object IntentUtils {

    private const val TAG = "IntentUtils"

    fun openCameraIntent(callback:(Uri)->Unit): Intent {
        val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        val file = createFile()
        val fileProviderAuthority = AppUtils.getMetaData("fileProviderAuthority")?:""
        MyLogger.d(TAG, "fileProviderAuthority:$fileProviderAuthority")
        val mImageUriFromCamera = FileProvider.getUriForFile(MyApplication.INSTANCE, fileProviderAuthority, file)
        callback(mImageUriFromCamera)
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUriFromCamera)
        return intent
    }

    fun openAlbumIntent(multiple:Boolean = true): Intent {
        val intent = Intent(Intent.ACTION_PICK)
        intent.type = "image/*"
        intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION)
        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, multiple)
        return intent
    }

    private fun createFile(): File {
        val sdcardDir = MyApplication.INSTANCE.filesDir
        val myPhotoDir = File(sdcardDir, "feed")
        if (!myPhotoDir.exists()) {
            myPhotoDir.mkdir()
        }
        val file = File(myPhotoDir, "${System.currentTimeMillis()}.jpg")
        if (!file.exists()) file.createNewFile()

        val pathArray = arrayOf(file.absolutePath)
        val typeArray = arrayOf("image/jpeg")
        MediaScannerConnection.scanFile(MyApplication.INSTANCE, pathArray, typeArray) { s, uri -> Log.d("ImageUtils", "onScanCompleted  s->$s") }
        return file
    }
}